import os
from typing import List


class FileRenamer:
    """
    文件重命名工具类
    支持在文件名前后插入序号，并可选择是否保留原文件名
    """

    def __init__(self, folder_path: str):
        """
        初始化
        Args:
            folder_path: 目标文件夹路径
        """
        self.folder_path = folder_path
        self.files_info = []

        # --- 新增：重命名参数作为类成员 ---
        self.position = 'r'           # 序号插入位置 ('l' 或 'r')
        self.keep_original_name = True  # 是否保留原文件名
        self.start_number = 1           # 起始序号
        self.padding = 2               # 序号位数（例如 3 → 001）
        self.prefix = ""                # 前缀文本
        self.suffix = ""                # 后缀文本

    # -----------------------------
    # 📌 Setter 函数定义
    # -----------------------------
    def set_position(self, position: str):
        """设置插入位置"""
        if position not in ['l', 'r']:
            raise ValueError("position 必须是 'l' 或 'r'")
        self.position = position

    def set_keep_original_name(self, keep: bool):
        """设置是否保留原文件名"""
        self.keep_original_name = keep

    def set_start_number(self, start_number: int):
        """设置起始编号"""
        if start_number < 0:
            raise ValueError("start_number 必须大于等于 0")
        self.start_number = start_number

    def set_padding(self, padding: int):
        """设置编号填充位数"""
        if padding < 0:
            raise ValueError("padding 不能为负数")
        self.padding = padding

    def set_prefix(self, prefix: str):
        """设置前缀文本"""
        self.prefix = prefix

    def set_suffix(self, suffix: str):
        """设置后缀文本"""
        self.suffix = suffix

    # -----------------------------
    # 🔍 文件扫描
    # -----------------------------
    def scan_files(self) -> List[dict]:
        """扫描文件夹，提取文件名信息"""
        if not os.path.exists(self.folder_path):
            raise FileNotFoundError(f"文件夹不存在: {self.folder_path}")

        if not os.path.isdir(self.folder_path):
            raise ValueError(f"路径不是文件夹: {self.folder_path}")

        self.files_info = []

        for filename in os.listdir(self.folder_path):
            file_path = os.path.join(self.folder_path, filename)

            if os.path.isfile(file_path):
                name_without_ext, extension = os.path.splitext(filename)
                self.files_info.append({
                    'original_path': file_path,
                    'original_name': filename,
                    'name_without_ext': name_without_ext,
                    'extension': extension
                })

        self.files_info.sort(key=lambda x: x['original_name'])
        return self.files_info

    # -----------------------------
    # 🔄 文件重命名
    # -----------------------------
    def rename_files(self) -> List[str]:
        """根据当前类成员设置重命名文件"""
        if not self.files_info:
            self.scan_files()

        if not self.files_info:
            print("⚠️ 文件夹中没有文件")
            return []

        renamed_paths = []
        current_number = self.start_number

        print(f"开始重命名 {len(self.files_info)} 个文件...")
        print(f"参数: 位置={self.position}, 保留原名={self.keep_original_name}, 起始序号={self.start_number}")

        for file_info in self.files_info:
            try:
                # 格式化序号
                number_part = f"{current_number:0{self.padding}d}" if self.padding > 0 else str(current_number)

                # 构造新文件名
                if self.keep_original_name:
                    if self.position == 'l':
                        new_name = f"{number_part}{self.prefix}{self.suffix}{file_info['name_without_ext']}"
                    else:
                        new_name = f"{self.prefix}{file_info['name_without_ext']}{self.suffix}{number_part}"
                elif self.position == 'l':
                    new_name = f"{number_part}{self.prefix}{self.suffix}"
                else:
                    new_name = f"{self.prefix}{self.suffix}{number_part}"

                # 拼接扩展名与路径
                new_filename = f"{new_name}{file_info['extension']}"
                new_path = os.path.join(self.folder_path, new_filename)

                os.rename(file_info['original_path'], new_path)
                renamed_paths.append(new_path)

                print(f"✅ 重命名: {file_info['original_name']} → {new_filename}")
                current_number += 1

            except Exception as e:
                print(f"❌ 重命名失败 {file_info['original_name']}: {e}")

        print(f"🎉 重命名完成！共处理 {len(renamed_paths)} 个文件")
        return renamed_paths


# ✅ 使用示例
if __name__ == "__main__":
    folder = r"C:\Users\33720\Desktop\temp\img3"

    renamer = FileRenamer(folder)
    renamer.set_position('l')           # 序号放前面
    renamer.set_keep_original_name(False)
    renamer.set_start_number(1)
    renamer.set_padding(2)              # 三位编号（001, 002）
    # renamer.set_prefix("_")             # 在编号前添加下划线
    renamer.set_suffix("_v1")           # 添加后缀
    renamer.rename_files()
